package org.asiainfo.system.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.mybatisflex.core.update.UpdateChain;
import org.asiainfo.common.core.constant.CacheNames;
import org.asiainfo.common.core.utils.StringUtils;
import org.asiainfo.common.mybatis.stream.core.page.TableDataInfo;
import org.asiainfo.common.mybatis.stream.core.page.PageQuery;
import org.asiainfo.system.domain.vo.SysClientVo;
import org.asiainfo.system.domain.bo.SysClientBo;
import org.asiainfo.system.domain.SysClient;
import org.asiainfo.system.service.SysClientService;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.asiainfo.common.core.utils.MapstructUtils;
import lombok.extern.slf4j.Slf4j;
import cn.hutool.core.util.ObjectUtil;
import com.mybatisflex.core.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import org.asiainfo.system.mapper.SysClientMapper;
import com.mybatisflex.core.paginate.Page;

import java.util.Collection;
import java.util.List;

/**
 * 系统授权表(SysClient)表服务实现类
 *
 * @author dotor-ww
 * @since 2024-01-15 21:17:44
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class SysClientServiceImpl extends ServiceImpl<SysClientMapper, SysClient> implements SysClientService {

    /**
     * 构建查询条件
     *
     * @param sysClientBo 筛选条件
     * @return 查询结果
     */
    private QueryWrapper buildQueryWrapper(SysClientBo sysClientBo) {
        QueryWrapper query = query();
        query.eq(SysClient::getClientId, sysClientBo.getClientId(), StringUtils.isNotBlank(sysClientBo.getClientId()));
        query.eq(SysClient::getClientKey, sysClientBo.getClientKey(), StringUtils.isNotBlank(sysClientBo.getClientKey()));
        query.eq(SysClient::getClientSecret, sysClientBo.getClientSecret(), StringUtils.isNotBlank(sysClientBo.getClientSecret()));
        query.eq(SysClient::getStatus, sysClientBo.getStatus(), StringUtils.isNotBlank(sysClientBo.getStatus()));
        query.orderBy(SysClient::getCreateTime, false);
        return query;
    }

    /**
     * 查询
     *
     * @param sysClientBo 筛选条件
     * @return 查询结果
     */
    @Override
    public List<SysClientVo> queryList(SysClientBo sysClientBo) {
        QueryWrapper query = buildQueryWrapper(sysClientBo);
        return listAs(query, SysClientVo.class);
    }

    /**
     * 通过id查询单条数据
     *
     * @param clientId 客户端ID
     * @return 实例对象
     */
    @Override
    public SysClientVo queryById(String clientId) {
        SysClientVo clientVo = getOneAs(query().eq(SysClient::getClientId, clientId), SysClientVo.class);
        clientVo.setGrantTypeList(List.of(clientVo.getGrantType().split(",")));
        return clientVo;
    }

    /**
     * 分页查询
     *
     * @param sysClientBo 筛选条件
     * @param pageQuery   分页对象
     * @return 查询结果
     */
    @Override
    public TableDataInfo<SysClientVo> queryPageList(SysClientBo sysClientBo, PageQuery pageQuery) {
        QueryWrapper query = buildQueryWrapper(sysClientBo);
        query.orderBy(SysClient::getCreateTime, false);
        Page<SysClientVo> result = pageAs(pageQuery.buildPage(), query, SysClientVo.class);
        result.getRecords().forEach(r -> r.setGrantTypeList(List.of(r.getGrantType().split(","))));
        return TableDataInfo.build(result);
    }

    /**
     * 新增数据
     *
     * @param sysClientBo 实例对象
     * @return 实例对象
     */
    @Override
    public Boolean insertByBo(SysClientBo sysClientBo) {
        SysClient sysClient = MapstructUtils.convert(sysClientBo, SysClient.class);
        if (ObjectUtil.isNotNull(sysClient)) {
            sysClient.setGrantType(String.join(",", sysClientBo.getGrantTypeList()));
        }
        String clientKey = sysClientBo.getClientKey();
        String clientSecret = sysClientBo.getClientSecret();
        if (ObjectUtil.isNotNull(sysClient)) {
            sysClient.setClientId(SecureUtil.md5(clientKey + clientSecret));
        }
        return save(sysClient);
    }

    /**
     * 修改数据
     *
     * @param sysClientBo 实例对象
     * @return 实例对象
     */
    @CacheEvict(cacheNames = CacheNames.SYS_CLIENT, key = "#sysClientBo.clientId")
    @Override
    public Boolean updateByBo(SysClientBo sysClientBo) {
        SysClient sysClient = MapstructUtils.convert(sysClientBo, SysClient.class);
        if (ObjectUtil.isNotNull(sysClient)) {
            sysClient.setGrantType(String.join(",", sysClientBo.getGrantTypeList()));
        }
        return updateById(sysClient);
    }

    /**
     * 通过主键删除数据
     *
     * @param clientIds 主键
     * @return 是否成功
     */
    @CacheEvict(cacheNames = CacheNames.SYS_CLIENT, allEntries = true)
    @Override
    public Boolean deleteWithValidByIds(Collection<String> clientIds) {
        return removeByIds(clientIds);
    }

    /**
     * 修改客户端状态
     *
     * @param sysClientBo 实体
     * @return 编辑结果
     */
    @CacheEvict(cacheNames = CacheNames.SYS_CLIENT, key = "#sysClientBo.clientId")
    @Override
    public Boolean updateClientStatus(SysClientBo sysClientBo) {
        SysClient sysClient = MapstructUtils.convert(sysClientBo, SysClient.class);
        if (ObjectUtil.isNull(sysClient)) throw new SecurityException("修改客户端状态异常");
        return UpdateChain.of(SysClient.class)
                .set(SysClient::getStatus, sysClient.getStatus(), StringUtils.isNotBlank(sysClient.getStatus()))
                .where(SysClient::getClientId).eq(sysClient.getClientId())
                .update();
    }

    /**
     * 查询客户端信息
     *
     * @param clientId 客户端ID
     * @return 查询结果
     */
    @Cacheable(cacheNames = CacheNames.SYS_CLIENT, key = "#clientId")
    @Override
    public SysClientVo queryByClientId(String clientId) {
        return getOneAs(query().eq(SysClient::getClientId, clientId), SysClientVo.class);
    }
}
